package com.beinhospital_sw21_h2_05.beinhospitalsw21h205.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.entity.Linshi;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.entity.Patient;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.entity.UserTable;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.mapper.UserMapper;
import com.beinhospital_sw21_h2_05.beinhospitalsw21h205.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    /**
     * 用户注册方法
     *
     * @param user    用户信息对象
     * @param patient 病人信息对象
     * @return 注册结果，成功返回1，失败返回0
     */
    @Override
    public int register(UserTable user, Patient patient) {
        // 检查用户名是否已存在
        int flag = userMapper.flag(user.getUsername());
        log.info("flag: {}", flag);

        // 若用户名不存在，则进行注册
        if (flag == 0) {
            // 插入用户表
            userMapper.insertUser(user);

            // 获取插入用户表后的用户ID
            int userID = userMapper.getUserId(user);

            // 设置病人信息中的用户ID
            patient.setUserID(userID);

            // 插入病人表
            userMapper.insertPatient(patient);

            return 1; // 注册成功
        }

        return 0; // 注册失败，用户名已存在
    }


    /**
     * 登陆功能
     * @param user
     * @return
     */
    @Override
    public SaResult usernameLoginService(UserTable user) {
        // 获取用户输入的用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();

        // 校验用户名和密码是否匹配数据库记录
        if (username.equals(userMapper.getUsername(username)) && password.equals(userMapper.getPassword(username))) {
            // 用户名密码匹配成功，进行登录
            StpUtil.login(userMapper.getId(username));
            // 输出当前登录用户的Token信息
            System.err.println(StpUtil.getTokenInfo());

            // 构造临时对象，用于返回登录结果
            Linshi linshi = new Linshi();
            linshi.setRole(userMapper.getRole(username));
            linshi.setToken(StpUtil.getTokenValue());

            return SaResult.data(linshi);  // 返回登录成功结果
        }

        return SaResult.error("账号或密码错误，请重试");  // 返回登录失败结果
    }

}
